var starMap = (function() {
  var A = {};
  var h = 0;
  var hei = $("body").height() - h;
  var wid = $("body").width();
  var maptk;
  var map;
  var geocoder;
  var zzt;
  var cityName;
  var markers = {};
  var cate;
  var datas = {};
  var offsetx = 0;
  
  A.initData = function(){
    var icon = A.local.getParam('icon');
    cate = {cateId: A.local.getParam('cid'), icon: icon ? icon : null};
    if(cate.icon){
      var img = new Image();
      img.src = cate.icon;
      img.onload = function(){
        offsetx = img.width / 2;
      }
    }
    A.loadData(1);
  };
  A.loadData = function(pageNum){
    A.local.ajax({
      url: '/warInfo/map',
      data: {"cateId": cate.cateId, "pager": {"pageNum": pageNum, "pageSize": 33}},
      callback: function(data){
        var items = data[cate.cateId];
        if(items && items.length > 0){
          items.forEach(function(item){
            A.addMarker(item);
          });
          pageNum ++;
          A.loadData(pageNum);
        }else{
          A.bindMarkerInfoWin();
        }
      }
    });
  };
  A.getMap = function(){
    return map;
  };
  
  A.viewZzt = function(data) {
    if (zzt)
      return;
    zzt = new T.Control({
      position : T_ANCHOR_TOP_LEFT
    });
    zzt.onAdd = function(map) {
      var div = $('<div class="zztDiv">');
      div.css({
        "width" : wid * 0.6,
        "max-height" : hei * 0.8
      });
      var html = '<p class="zztTtile">作战指标<span>·</span></p>';
      // html += '<div></div>';
      div.append(html);
      var listDiv = $('<div class="listDiv">');
      listDiv.html(A.local.createDataList(data));
      div.append(listDiv);
      return div[0];
    };
    map.addControl(zzt);
    $(".recordItem").click(function(ev) {
      if (ev.target.nodeName == "INPUT") {
        return;
      }
      var che = $(":checkbox", $(this));
      var dataUrl = che.attr("data-url");
      var cateId = che.attr("data-cid");
      var c = che[0].checked;
      che[0].checked = !c;
      A.local.loadData(dataUrl, cateId, !c);
    });
    $(":checkbox").change(function() {
      var dataUrl = $(this).attr("data-url");
      var cateId = $(this).attr("data-cid");
      A.local.loadData(dataUrl, cateId, this.checked);
    });
    $(".titlep").click(function() {
      $("ul", $(this).parent()).slideToggle();
    });
    $(".zztTtile").click(function() {
      $(".listDiv").slideToggle();
    });
    setTimeout(function() {
      $(".titlep").trigger("click");
      $(".zztTtile").trigger("click");
    }, 500);
  };
  A.removeZzt = function() {
    if (zzt) {
      map.removeControl(zzt);
      zzt = null;
    }
  };
  A.initTools = function() {
    A.local.tuceng();
    A.local.searchAddr();
    $(".tdt-control-copyright").hide();
    map.addEventListener("contextmenu", function(e){
      geocoder.getLocation(e.lnglat, A.local.parseAddressNi);
    });
  }

  A.viewMap = function(tk, id, city, zoom, config) {
    maptk = tk;
    cityName = city;
    $("#" + id).height(hei);
    map = new T.Map(id, config);
    map.centerAndZoom(new T.LngLat(116.40969, 39.89945), zoom);
    map.enableScrollWheelZoom();
    geocoder = new T.Geocoder();
    geocoder.getPoint(city, A.local.fixedLocation);
  };

  A.local = {};
  A.local.loadData = function(url, cateId, checked) {
    console.log(url + "\t" + cateId + "\t" + checked);
    if (!checked) {
      var mrks = markers["cateId_" + cateId];
      if (mrks && mrks.length > 0) {
        for ( var i in mrks) {
          map.removeOverLay(mrks[i]);
        }
        markers["cateId_" + cateId] = null;
      }
    } else {
      A.local.ajax({
        url : url,
        data : {
          "cateId" : cateId
        },
        callback : function(data) {
          var ms = new Array();
          data.forEach(function(item) {
            var marker = new T.Marker(new T.LngLat(item.lng, item.lat), {
              icon : new T.Icon({
                iconUrl : item.icon
              })
            });
            map.addOverLay(marker);
            ms.push(marker);
          });
          markers["cateId_" + cateId] = ms;
        }
      })
    }
  };
  A.local.createDataList = function(data) {
    var html = "<ul>";
    data.forEach(function(item) {
      html += '<li class="itemArea"><p class="titlep">' + item.name + '</p>';
      html += '<ul>';
      item.children.forEach(function(record) {
        var url = record.dataParams;
        if (url) {
          url = url.url;
        }
        html += '<li class="recordItem"><input type="checkbox" data-cid="' + record.cateId + '" data-url="' + url + '"><img src="' + record.icon + '" height="18px"> <span>' + record.name + '<span></li>';
      });
      html += '</ul>';
      html += '</li>';
    });
    html += "</ul>";
    return html;
  };
  A.local.searchAddr = function() {
    var dw = new T.Control({
      position : T_ANCHOR_TOP_LEFT
    });
    dw.onAdd = function(map) {
      var div = $('<div class="dwDiv">');
      div.html('<input type="text" id="searchIpt" class="ipt400" placeholder="输入需要定位的地址"> <button class="dwBtn">定位</button>');
      return div[0];
    };
    map.addControl(dw);
    $(".dwBtn").click(function() {
    	var addr=$("#searchIpt").val();
    	if(! addr) {
    	  alert("请输入需定位的地址");
    	  return;
    	}
      geocoder.getPoint(addr, A.local.searchResult);
    });
  };
  A.local.tuceng = function() {
    var tc = new T.Control({
      position : T_ANCHOR_TOP_RIGHT
    });
    tc.onAdd = function(map) {
      var div = $('<div class="tcDiv">');
      div.html('<button class="tcBtn">地<br>图</button>');
      var html = '<div class="tcBtns">';
      html += '<button class="chooseMapBtn" data-type="vec" data-name="地<br>图"><img src=""><br>地图</button>';
      html += '<br><button class="chooseMapBtn" data-type="img" data-name="影<br>像"><img src=""><br>影像</button>';
      html += '<br><button class="chooseMapBtn" data-type="ter" data-name="地<br>形"><img src=""><br>地形</button>';
      div.append(html);
      return div[0];
    };
    map.addControl(tc);
    $(".tcBtn").click(function() {
      $(".tcBtns").slideToggle("fast", function() {
        $(".chooseMapBtn").unbind().click(function() {
          var type = $(this).attr("data-type");
          var name = $(this).attr("data-name");
          $(".tcBtn").html(name);
          $(".tcBtn").click();
          $(this).unbind();
          A.local.changeMapType(type);
        });
      });
    });
  };
  A.local.changeMapType = function(n) {
    var o = parseInt(Math.random() * 7);
    var urlImg = "https://t" + o + ".tianditu.gov.cn/" + n + "_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=" + n + "&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=" + maptk;
    n = "cva";
    var urlName = "https://t" + o + ".tianditu.gov.cn/" + n + "_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=" + n + "&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=" + maptk;
    map.clearLayers();
    var lay1 = new T.TileLayer(urlImg, {
      minZoom : 1,
      maxZoom : 18
    });
    var lay2 = new T.TileLayer(urlName, {
      minZoom : 1,
      maxZoom : 18
    });
    map.addLayer(lay1);
    map.addLayer(lay2);
  };
  var searchInfoWin;
  A.local.searchResult = function(result) {
    if (result.getStatus() == 0) {
      if(searchInfoWin){
        map.removeOverLay(searchInfoWin);
      }
      searchInfoWin = new T.InfoWindow("在下面箭头处右击鼠标，可添加信息");
      map.openInfoWindow(searchInfoWin, result.getLocationPoint());
      map.panTo(result.getLocationPoint());
    } else {
      alert(result.getMsg());
    }
  };
  A.local.fixedLocation = function(result) {
    if (result.getStatus() == 0) {
      map.panTo(result.getLocationPoint());
    } else {
      alert(result.getMsg());
    }
  };
  var editWarInfoWin;
  A.local.parseAddressNi = function(result) {
    if (result.getStatus() == 0) {
      if (editWarInfoWin) {
        map.removeOverLay(editWarInfoWin);
        editWarInfoWin = null;
        $("#iframeWin").remove();
      }
      var html = '<div style="margin:0px;width:600px;height:500px"><iframe id="iframeWin" src="/warInfo/addBefore/'+cate.cateId+'" frameborder="0" width="100%" height="100%" marginheight="0" marginwidth="0" scrolling="yes" seamless></div>';
      var lnglat = result.getLocationPoint();
      editWarInfoWin = new T.InfoWindow(html, {minWidth: 600, maxWidth: 600, autoPan: true, autoPanPadding: new T.Point(100, 60)});
      map.openInfoWindow(editWarInfoWin, lnglat);
      try{
        $("iframe[id=iframeWin]")[0].contentWindow.sendData({cate: cate, map: map, result: result});
      }catch(e){
        $("#iframeWin").on("load", function(){
          document.getElementById("iframeWin").contentWindow.sendData({cate: cate, map: map, result: result});
        });
      }
    } else {
      alert(result.getMsg());
    }
  };
  
  A.addMarker = function(params){
    var marker;
    if(cate.icon){
      marker = new T.Marker(new T.LngLat(params.lng, params.lat), {icon: new T.Icon({iconUrl: cate.icon})});
    }else{
      marker = new T.Marker(new T.LngLat(params.lng, params.lat));
    }
    map.addOverLay(marker);
    datas[params.id] = marker;
  };
  
  A.bindMarkerInfoWin = function(){
    for(var id in datas){
      var marker = datas[id];
      addClickHandler(id, marker);
    }
  }
  function addClickHandler(id,marker){
    marker.addEventListener("click", function (e) {
      A.openInfoWin(id, marker);
    });
//    marker.addEventListener("mouseover", function (e) {
//      A.openLabel(id, marker);
//    });
//    marker.addEventListener("mouseout", function (e) {
//      A.closeLabel(id, marker);
//    });
  }
//  var label;
//  A.openLabel = function(id, marker){
//    label = new T.Label({
//      text: "<b>文字标注!!!<b>",
//      position: marker.getLngLat(),
//      offset: new T.Point(3, -30)
//    });
//    map.addOverLay(label);
//  };
//  A.closeLabel = function(id, marker){
//    map.removeOverLay(label);
//  };
  
  A.openInfoWin = function(id, marker){
    var html = '<div style="margin:0px;width:600px;height:500px"><iframe id="iframeWin" src="/warInfo/editBefore/'+id+'" frameborder="0" width="100%" height="100%" marginheight="0" marginwidth="0" scrolling="yes" seamless></div>';
    var editWarInfoWin = new T.InfoWindow(html, {minWidth: 600, maxWidth: 600, autoPan: true, autoPanPadding: new T.Point(100, 60), offset: new T.Point(offsetx, 5)});
    marker.openInfoWindow(editWarInfoWin);
    try{
      $("iframe[id=iframeWin]")[0].contentWindow.sendData({map: map, marker: marker});
    }catch(e){
      $("#iframeWin").on("load", function(){
        document.getElementById("iframeWin").contentWindow.sendData({map: map, marker: marker});
      });
    }
  }
  
  A.viewMarker = function(params){
    A.openInfoWin(params.id, datas[params.id]);
  }
  
  A.local.getParam = function(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");     
    var r = window.location.search.substr(1).match(reg);
    //search,查询？后面的参数，并匹配正则    
    if(r!=null)
      return  unescape(r[2]); 
    return null;
  };
  A.local.ajax = function(options) {
    $.ajax({
      async: null == options.async ? true : options.async,
      url : options.url,
      contentType : 'application/json',
      data : JSON.stringify(options.data),
      type : 'post',
      dataType : 'json',
      success : function(res) {
        if (res.code == 0) {
          if (options.callback) {
            options.callback(res.data);
          }
        } else {
          alert(res.msg)
        }

      },
      error : function(a, b) {
        console.log(b);
        alert(res.msg)
      }
    });
  };
  return A;
})();